package com.css.dzj.dzjap.modules.lawenforcesuper.service.impl;

import com.css.dzj.dzjap.common.util.Constant;
import com.css.dzj.dzjap.common.util.R;
import com.css.dzj.dzjap.common.util.RandomUtil;
import com.css.dzj.dzjap.common.util.ServiceUtil;
import com.css.dzj.dzjap.modules.executorinfo.entity.ApExecutorInfoEntity;
import com.css.dzj.dzjap.modules.executorinfo.service.ExecutorInfoService;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.ApExtractLawerEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.ExtractLawerRelationEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.QApExtractLawerEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.QExtractLawerRelationEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ApExtractLawerMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ExtractLawerRelationMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.service.ApDeptExtractService;
import com.css.dzj.dzjap.modules.lawenforcesuper.service.ApExtractLawerDeptService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 安评单位抽取---执法人员抽取
 * @author limanman
 */
@Service
public class ApExtractLawerDeptServiceImpl implements ApExtractLawerDeptService {
    @Autowired
    private ApExtractLawerMapper apExtractLawerMapper;
    @Autowired
    private ExtractLawerRelationMapper extractLawerRelationMapper;
    @Autowired
    private ExecutorInfoService executorInfoService;
    @Autowired
    private  JPAQueryFactory jpaQueryFactory;
    @Autowired
    private ApDeptExtractService apDeptExtractService;
    @Autowired
    private ServiceUtil serviceUtil;

    /**
     * 添加两张表
     * 执法人员抽取比例表
     * 执法人员与比例表的关联表
     * @param apExtractLawerEntity
     * @return
     */
    @Override
    @Transactional
    public R saveLawerExtractInfo(ApExtractLawerEntity apExtractLawerEntity, HttpServletRequest request) {
        try {
            if (apExtractLawerEntity ==null || "".equals(apExtractLawerEntity)){
                throw new RuntimeException("新增不能为空");
            }

            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String location = "";
            String address="";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                String orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
                address = userInfo.getAddress();
            }
            apExtractLawerEntity.setId(UUID.randomUUID().toString());
            apExtractLawerEntity.setCreateTime(new Date());
            apExtractLawerEntity.setCreatePerson(suserName);
            String extractId = apExtractLawerEntity.getId();

            ExtractLawerRelationEntity extractLawerRelationEntity;
            List<ExtractLawerRelationEntity> extractLawerRelationEntities = new ArrayList<ExtractLawerRelationEntity>();

            /**
             * 抽取执法人员总数
             */
            Integer extractNum = apExtractLawerEntity.getExtractNum();
            if(extractNum <2){
                throw new RuntimeException("抽取执法人员总数不能小于2");
                /**
                 * 在前端判断总数为1的情况
                 */
            }
            Integer bdcountryNum = 0;
            Integer bdprovienceNum = 0;
            if (Constant.LOCATIONZG.contains(location)){
                /**
                 * 如果登陆者为国家人员
                 */
                /**
                 *抽取国家执法人员的人数
                 */
                double countryNum = apExtractLawerEntity.getCountryRatio()*extractNum/100.0;
                Integer country = Integer.parseInt(new BigDecimal(countryNum).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());
                if (apExtractLawerEntity.getCountryRatio()+apExtractLawerEntity.getProvinceRatio()!=100){
                    throw new RuntimeException("抽取比例错误，抽取比例总和应为100%！");
                }
                double dc = countryNum-country;
                int i=0;
                if (dc==0.5){
                    i++;
                }
                bdcountryNum =Integer.parseInt(new BigDecimal(countryNum).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
                /**
                 *抽取省执法人员的人数
                 */
                double provienceNum = apExtractLawerEntity.getProvinceRatio()*extractNum/100.0;
                Integer provience = Integer.parseInt(new BigDecimal(provienceNum).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());
                double dp = provienceNum-provience;
                if (dp==0.5){
                    if (i>0){
                        bdprovienceNum =Integer.parseInt(new BigDecimal(provienceNum).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());
                    }
                }else {
                    bdprovienceNum =Integer.parseInt(new BigDecimal(provienceNum).setScale(0,BigDecimal.ROUND_HALF_UP).toString());
                }
            } else {
                /**
                 * 如果登陆者为省级人员，则把抽取总数给抽取省级人员总数
                 */
                bdprovienceNum = extractNum;
            }
            /**
             * 数据库数量
             */
            if(bdcountryNum<0){
                throw new RuntimeException("");
            }else{
                List<ApExecutorInfoEntity> countryApExecutorInfoEntities =  executorInfoService.findExecutorByExecutorLevel(Constant.STATE_LEVEL,request);//国家
                if(bdcountryNum <= countryApExecutorInfoEntities.size()){
                    /**
                     * 随机选择
                     */
                    List<ApExecutorInfoEntity> countryRandomList = RandomUtil.ramdonExtract(countryApExecutorInfoEntities,bdcountryNum.toString());
                    if (!StringUtils.isEmpty(countryRandomList)&& countryRandomList.size()>0){
                        for (ApExecutorInfoEntity apExecutorInfoEntity:countryRandomList){
                            extractLawerRelationEntity = new ExtractLawerRelationEntity();
                            extractLawerRelationEntity.setExtractId(extractId);
                            extractLawerRelationEntity.setRelateId(apExecutorInfoEntity.getId());
                            extractLawerRelationEntity.setCreateTime(new Date());
                            extractLawerRelationEntity.setCreatePerson(suserName);
                            extractLawerRelationEntities.add(extractLawerRelationEntity);
                        }
                    }
                }else {
                    throw new RuntimeException("符合抽取条件的执法人员数量不足！");
                }
            }
            if(bdprovienceNum<0){
                throw new RuntimeException("");
            }else{
                List<ApExecutorInfoEntity> provienceApExecutorInfoEntities =  executorInfoService.findExecutorByExecutorLevel(Constant.PROVIENCE_LEVEL,request);//省
                if(bdprovienceNum <= provienceApExecutorInfoEntities.size()){
                    /**
                     * 随机选择
                     */
                    List<ApExecutorInfoEntity> provienceRandomList = RandomUtil.ramdonExtract(provienceApExecutorInfoEntities,bdprovienceNum.toString());
                    if (!StringUtils.isEmpty(provienceRandomList)&& provienceRandomList.size()>0){
                        for (ApExecutorInfoEntity apExecutorInfoEntity:provienceRandomList){
                            extractLawerRelationEntity = new ExtractLawerRelationEntity();
                            extractLawerRelationEntity.setExtractId(extractId);
                            extractLawerRelationEntity.setRelateId(apExecutorInfoEntity.getId());
                            extractLawerRelationEntity.setCreateTime(new Date());
                            extractLawerRelationEntity.setCreatePerson(suserName);
                            extractLawerRelationEntities.add(extractLawerRelationEntity);
                        }
                    }
                }else {
                    throw new RuntimeException("符合抽取条件的执法人员数量不足！");
                }
            }

            if(!StringUtils.isEmpty(extractLawerRelationEntities)&&extractLawerRelationEntities.size()>0){
                extractLawerRelationMapper.saveAll(extractLawerRelationEntities);
            }
            apExtractLawerMapper.save(apExtractLawerEntity);
            apDeptExtractService.updApDeptExtractRelation(apExtractLawerEntity.getTaskId(),apExtractLawerEntity.getLinkId());
            return  R.ok();
        } catch(Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 查询某一抽取执法人员的比例表
     * @param taskId
     * @param recordId
     * @return
     */
    @Override
    public ApExtractLawerEntity queryLawerExtractOnly(String taskId, String recordId) {
        try {
            if (!"".equals(taskId) && taskId!=null && !"".equals(recordId) && recordId!=null){
                QApExtractLawerEntity qApExtractLawerEntity = QApExtractLawerEntity.apExtractLawerEntity;
                return jpaQueryFactory.selectFrom(qApExtractLawerEntity)
                        .where(qApExtractLawerEntity.taskId.eq(taskId), qApExtractLawerEntity.linkId.eq(recordId))
                        .fetchOne();
            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 查询抽取执法人员比例表和执法人员关联表
     * @param pageable
     * @param extractId
     * @return
     */
    @Override
    public QueryResults<ExtractLawerRelationEntity> queryLawerExtractInfo(Pageable pageable, String extractId) {
        try {
            QExtractLawerRelationEntity qExtractLawerRelationEntity = QExtractLawerRelationEntity.extractLawerRelationEntity;
            Predicate predicate = qExtractLawerRelationEntity.isNotNull().or(qExtractLawerRelationEntity.isNull());
            predicate = ("".equals(extractId) || extractId ==null ) ? predicate : ExpressionUtils.and(predicate,qExtractLawerRelationEntity.extractId.eq(extractId));
            return jpaQueryFactory.selectFrom(qExtractLawerRelationEntity)
                    .where(predicate)
                    .offset(pageable.getOffset())
                    .limit(pageable.getPageSize())
                    .fetchResults();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 查询一次安评单位抽取中某一单位抽取的执法人员
     * @param pageable
     * @param extractId
     * @return
     */
    @Override
    public QueryResults<ApExecutorInfoEntity> queryLawerById(Pageable pageable, String extractId) {
        try {
            if (!"".equals(extractId) && extractId!=null){
                List<ApExecutorInfoEntity> apExecutorInfoEntities = new ArrayList<ApExecutorInfoEntity>();
                QueryResults<ExtractLawerRelationEntity> extractLawerRelationEntities = queryLawerExtractInfo(pageable,extractId);
                if (!StringUtils.isEmpty(extractLawerRelationEntities) && extractLawerRelationEntities.getResults().size()>0){
                    for(ExtractLawerRelationEntity extractLawerRelationEntity:extractLawerRelationEntities.getResults()){
                        apExecutorInfoEntities.add(executorInfoService.getExecutorInfo(extractLawerRelationEntity.getRelateId()));
                    }
                    QueryResults<ApExecutorInfoEntity> queryResults = new QueryResults(apExecutorInfoEntities,(long)pageable.getPageSize(),pageable.getOffset(),extractLawerRelationEntities.getTotal());
                    return queryResults;
                }

            }
            return null;
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }
}
